/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.bom.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.bom.entity.Bom;
import vip.xiaonuo.modular.bom.enums.BomExceptionEnum;
import vip.xiaonuo.modular.bom.mapper.BomMapper;
import vip.xiaonuo.modular.bom.param.BomParam;
import vip.xiaonuo.modular.bom.service.BomService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 物料清单service接口实现类
 *
 * @author wz
 * @date 2022-08-11 09:15:20
 */
@Service
public class BomServiceImpl extends ServiceImpl<BomMapper, Bom> implements BomService {

    @Override
    public PageResult<BomParam> page(BomParam bomParam) {
        QueryWrapper<BomParam> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(bomParam)) {

            // 根据父项产品id 查询
            if (ObjectUtil.isNotEmpty(bomParam.getParentIds())) {
                queryWrapper.inSql("a.parent_id", bomParam.getParentIds());
            }
            // 根据子项产品id 查询
            if (ObjectUtil.isNotEmpty(bomParam.getSubitemIds())) {
                queryWrapper.inSql("a.subitem_id", bomParam.getSubitemIds());
            }
            // 根据备注 查询
            if (ObjectUtil.isNotEmpty(bomParam.getRemarks())) {
                queryWrapper.like("a.remarks", bomParam.getRemarks());
            }
        }
        queryWrapper.orderByDesc("a.create_time");
        return new PageResult<>(this.baseMapper.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<Bom> list(BomParam bomParam) {
        return this.list();
    }

    /**
     * 通过前端传来的父项ID查询所有的子项
     * @param bomParam
     * @return List<BomParam>
     */
    @Override
    public  List<BomParam> sonList(BomParam bomParam){
        if(ObjectUtil.isEmpty(bomParam.getParentId())){
            throw new ServiceException(4,"请传入父项产品ID");
        }
        List<BomParam> BomParamList = this.BomParamList();
        // 设置一个Map key 为父项id value 为 所有的子项
        Map<Long, List<BomParam>> bomMap = BomParamList.stream().collect(Collectors.groupingBy(BomParam::getParentId));
        List<BomParam> bomParamList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(bomMap)){
            recursion(0, bomParam.getParentId(), bomParamList, bomMap);
        }
        return bomParamList;
    }

    // 递归
    private void recursion(int i, Long parentId, List<BomParam> bomParamList, Map<Long, List<BomParam>> bomMap) {
        if(ObjectUtil.isEmpty(bomMap.get(parentId)) || i==5){
            return;
        }
        bomMap.get(parentId).forEach(bomParam -> {
            bomParamList.add(bomParam);
            recursion(i+1,bomParam.getSubitemId(),bomParamList,bomMap);
        });
    }


    public  List<BomParam> BomParamList(){
        return this.getBaseMapper().BomParamList();
    }





    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BomParam bomParam) {
        //校验
        checkParam(bomParam,false);
        Bom bom = new Bom();
        BeanUtil.copyProperties(bomParam, bom);
        this.save(bom);
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BomParam> bomParamList) {
        QueryWrapper<Bom> deleteBom = new QueryWrapper<>();
        bomParamList.forEach(bomParam -> {
            deleteBom.lambda().eq(Bom::getId,bomParam.getId()).or();
        });
        this.remove(deleteBom);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BomParam bomParam) {
        checkParam(bomParam,true);
        Bom bom = this.queryBom(bomParam);
        BeanUtil.copyProperties(bomParam, bom);
        this.updateById(bom);
    }

    @Override
    public Bom detail(BomParam bomParam) {
        return this.queryBom(bomParam);
    }

    /**
     * 获取物料清单
     *
     * @author wz
     * @date 2022-08-11 09:15:20
     */
    private Bom queryBom(BomParam bomParam) {
        Bom bom = this.getById(bomParam.getId());
        if (ObjectUtil.isNull(bom)) {
            throw new ServiceException(BomExceptionEnum.NOT_EXIST);
        }
        return bom;
    }

    @Override
    public void export(BomParam bomParam) {
        List<Bom> list = this.list(bomParam);
        PoiUtil.exportExcelWithStream("SnowyBom.xls", Bom.class, list);
    }
    private void checkParam(BomParam bomParam,boolean isExcludeSelf) {
        if(ObjectUtil.isEmpty(bomParam.getParentId()))
        {
            throw new ServiceException(6,"请选择父项产品");
        }
        if(ObjectUtil.isEmpty(bomParam.getSubitemId()))
        {
            throw new ServiceException(7,"请选择子项产品");
        }
        if(bomParam.getParentId().equals(bomParam.getSubitemId()))
        {
            throw new ServiceException(4,"父项产品和子项产品不能相同");
        }
        if(bomParam.getUnitCon()<=0||ObjectUtil.isEmpty(bomParam.getUnitCon()))
        {
            throw new ServiceException(5,"单位用量不能小于等于0且不能为空");
        }
        QueryWrapper<Bom> bomQueryWrapper = new QueryWrapper<>();
        bomQueryWrapper.lambda().eq(Bom::getParentId,bomParam.getParentId());
        bomQueryWrapper.lambda().eq(Bom::getSubitemId,bomParam.getSubitemId());
        if (isExcludeSelf){
            bomQueryWrapper.lambda().ne(Bom::getId,bomParam.getId());
        }
        int count = this.count(bomQueryWrapper);
        if (count >= 1 ){
            throw new ServiceException(8, "该父项产品已用该子项产品，请重新选择");
        }

    }

}
